package com.xw.utils;

import cn.hutool.core.io.IoUtil;
import com.xw.enums.ResultEnum;
import com.xw.vo.FileResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class EnclosureUtil {

    // 图片类型
    private static final List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
    }

    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     * 文件保存
     *
     * @return
     */
    public static String saveEnclosure(MultipartFile file) {
        FileResponseVO fileResponseVO = new FileResponseVO();
        String targetAddr = PathUtil.getImgPath(sdf.format(new Date()));
        // 获取不重复的随机名
        String realFileName = getRandomFileName();
        // 获取文件的扩展名如png,jpg等
        String extension = getFileExtension(Objects.requireNonNull(file.getOriginalFilename()));
        if (!fileTypes.contains(extension.toLowerCase())) {
            return fileResponseVO.error(ResultEnum.IMG_TYPE_ERR);
        }
        // 如果目标路径不存在，则自动创建
        makeDirPath(targetAddr);
        // 获取文件存储的相对路径(带文件名)
        String relativeAddr = targetAddr + realFileName + extension;
        log.debug("current relativeAddr is :" + relativeAddr);
        // 获取文件要保存到的目标路径
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        log.debug("current complete addr is :" + PathUtil.getImgBasePath() + relativeAddr);
        log.debug("basePath is :" + basePath);
        System.out.println(file.getOriginalFilename());
        try {
            file.transferTo(dest);
            FileUtil.compression(dest, 500, "K");
        } catch (IOException e) {
            log.error("file save err : {}", e.toString());
            e.printStackTrace();
        }
        return fileResponseVO.success(1, file.getOriginalFilename(), "file/viewUploadFile?id=" + relativeAddr, null);
    }


    @RequestMapping("/download")
    public static String downLoad(String relativeAddr, HttpServletResponse response) {
        String fileName = getFileExtension("upload/20200104/2020010416202246105.vbs");
        String filePath = PathUtil.getImgBasePath();
        File file = new File(filePath + "upload/20200104/2020010416202246105.vbs");
        if (file.exists()) { //判断文件父目录是否存在
            try {
                response.setContentType("application/octet-stream; charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(file);
                os = response.getOutputStream();
                IoUtil.copy(fis, os, IoUtil.DEFAULT_BUFFER_SIZE);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
        return null;
    }


    /**
     * 创建目标路径所涉及到的目录，即/home/work/rhyme/xxx.jpg, 那么 home work rhyme 这三个文件夹都得自动创建
     *
     * @param targetAddr 创建相对路径
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 获取输入文件流的扩展名
     *
     * @return 后缀
     */
    public static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 获取保存的文件名字
     *
     * @return
     */
    private static String getFileName(String relativeAddr) {
        int i = relativeAddr.lastIndexOf("/");
        return relativeAddr.substring(i + 1);

    }

    /**
     * 生成随机文件名，当前年月日小时分钟秒钟+五位随机数
     *
     * @return 随机
     */
    private static String getRandomFileName() {
        // 获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr + rannum;
    }


    public static void main(String[] args) {
//        String fileName = getFileName("upload/20200104/2020010416202246105.vbs");
//        System.out.println(fileName);

    }
}
